<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(suggestions, index) in suggestion"
      :key="index"
      @click="$emit('search', suggestions)"
    >
      <div slot="title" v-html="highlight(suggestions)"></div
    ></van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '../../../api/search'
import { debounce } from 'loadsh'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestion: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      // 当searchText发生改变的时候就会调用handler函数，注意handler函数名称是固定的
      handler: debounce(function(value) {
        this.loadsSearchSuggestion(value)
      }, 200),
      // handler(value) {
      //   this.loadsSearchSuggestion(value)
      // },
      immediate: true // 该handler回调将会在真挺开始之后立即被调用一次
    }
  },
  created() {},
  mounted() {},
  methods: {
    async loadsSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestion = data.data.options
      } catch (err) {
        this.$toast('获取数据失败，请稍后重试')
      }
    },
    highlight(text) {
      // 如果需要根据数据变量动态的创建正则表达式，则手动new RegExp
      const htmlStr = `<span style='color: blue;'>${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, htmlStr)
    }
  }
}
</script>
<style lang="less" scoped></style>
